package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;
import java.nio.file.Files;

/**
 * @author Administrator
 * @Description
 * @date 2022/5/17 11:45
 **/
public class DispatchServlet {
    private static File rootDir;
    private static File staticDir;

    static {
        try {
            rootDir = new File(
                    DispatchServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(rootDir, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }

    public void service(HttpServletRequest request, HttpServletResponse response) {
        //处理请求
        String uri = request.getUri();
         /**
        * @author
        * @description //
          *  http://localhost:8088/myweb/index.html
          *  path:/myweb/index.html
          *  总是去static目录下顺着path指定的路径定位文件的
        * @date 2022/5/17 14:46
         * @param request
        * @param response
        */
        File file = new File(staticDir, uri);

        if (file.isFile()) {
            response.setContentFile(file);

        } else {
            response.setStatesCode(404);
            response.setStatesReason("NotFound");
            file = new File(staticDir, "/root/404.html");
            response.setContentFile(file);


        }
        response.addHeader("Server", "WebServer");
    }
}
